package quick.frame.core.exception;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.elvishew.xlog.XLog;

import java.net.ConnectException;
import java.util.Objects;

import quick.frame.core.app.AppManager;
import quick.frame.core.app.BaseApplication;
import quick.frame.core.app.Quick;
import quick.frame.core.util.AppUtils;
import quick.frame.core.util.file.FileUtil;


public class BaseUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    // CrashHandler实例

    private static final class BaseUncaughtExceptionHandlerHolder {
        private final static BaseUncaughtExceptionHandler INSTANCE = new BaseUncaughtExceptionHandler();

    }

    // 系统默认的 UncaughtException 处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler = null;
    // 用来存储设备信息和异常信息
    private Context mContext;
    private String msg = "";
    //private static boolean onFlag = false;//是否退出应用

    /**
     * 保证只有一个CrashHandler实例
     */
    private BaseUncaughtExceptionHandler() {

    }

    public static BaseUncaughtExceptionHandler getInstance() {

        return BaseUncaughtExceptionHandlerHolder.INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        // 获取系统默认的 UncaughtException 处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该 CrashHandler 为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
          new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    showDialog();
                    Looper.loop();
                }
            }.start();
           // thread1.start();
          /*  AppUtils.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    showDialog();
                }
            });*/
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        if (ex instanceof BaseException) {
            BaseException be = (BaseException) ex;
            msg = be.getcodeMsg().getMsg();
        } else if (ex instanceof NullPointerException) {
            msg = "空指针异常！";

        } else if (ex instanceof ConnectException) {
            // ConnectException ce = (ConnectException)ex;
            msg = "网络异常";
        } else if (ex instanceof Exception) {
            Exception ce = (Exception) ex;
            msg = ce.getMessage();
        }
        // 收集设备参数信息
        XLog.e("系统错误", ex);
        return true;

    }

    private void showDialog() {

        MaterialDialog buder = new MaterialDialog.Builder(mContext)
        .title("温馨提示")
                .content(msg)
                .positiveText("退出")
                .negativeText("重启")
                //点击事件添加 方式1
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        AppManager.getAppManager().AppExit(Quick.getApplicationContext());
                        // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                    } else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        AppUtils.relaunchApp();
                    }
                    dialog.dismiss();
                }).build();
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
            Objects.requireNonNull(buder.getWindow()).setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }else{
            Objects.requireNonNull(buder.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

        }
        buder.show();
             /*   .("确认退出", (DialogInterface.OnClickListener) (dialog, which) -> {
                    "由于发生了一个未知错误，应用出现异常，我们对此引起的不便表示抱歉！" + "错误信息在手机内存对应的" + FileUtil.LOG_DIR + "目录中，请发送给我们帮助我们快速解决问题，谢谢！"
                    Log.e("系统异常", "---" + msg);

                    AppManager.getAppManager().AppExit(Quick.getApplicationContext());
                    dialog.dismiss();

                }).setNegativeButton("重启应用", (dialog1, which) -> {
            AppUtils.relaunchApp();
            dialog1.dismiss();
        })
                //.setCanceledOnTouchOutside(false)// 设置点击屏幕其他地方，dialog不消失
                .setCancelable(false)// 设置点击返回键和HOme键，dialog不消失;
                .show();

*/

	/*	if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
			Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		}else{
			Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

		}*/


    }

    public Class<?> getTopActivity() {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        String className = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        Class<?> cls = null;
        try {
            cls = Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return cls;
    }

}
